<template>
    <Teleport to='body'>
        <transition>
            <div v-if='props.modelValue' class='publish-works-container'>
                <!--            遮罩-->
                <div class='modal' @click='closePublishWorks'></div>
                <!--            主要窗体-->
                <div class='publish-main'>
                    <div class='header'>
                        <span class='title'>提交作品</span>
                        <span class='close' @click='closePublishWorks'>
                            <el-icon size='20' color='#CE6043'>
                            <Close />
                        </el-icon>
                        </span>
                    </div>
                    <div class='publish-form'>
                        <el-form ref='publishWorksRef' label-position='top' :rules='rules' :model='form'>
                            <el-form-item prop='title' label='作品名称'>
                                <el-input v-model='form.title' clearable class='ff' placeholder='请输入作品名称' />
                            </el-form-item>
                            <el-form-item prop='description' label='作品介绍'>
                                <el-input
                                    v-model='form.description' type='textarea' class='ff'
                                    placeholder='请输入作品名称' />
                            </el-form-item>
                            <el-form-item prop='attachments' label='作品附件'>
                                <el-upload
                                    class='ff'
                                    ref='fileUpload'
                                    :action='uploadFileUrl'
                                    :before-upload='handleBeforeUpload'
                                    :headers='headers'
                                    :limit='limit'
                                    :on-error='handleUploadError'
                                    :on-exceed='handleExceed'
                                    :on-success='handleUploadSuccess'
                                    :show-file-list='false'
                                    multiple
                                    drag
                                >
                                    <div class='upload-area'>
                                        <el-icon :size='88' color='#F2F6FC'>
                                            <UploadFilled />
                                        </el-icon>
                                        <span class='tips'>大小不超过{{ fileSize }}MB,格式为:{{ fileType.join('/')
                                            }}格式的文件</span>
                                    </div>
                                </el-upload>
                            </el-form-item>
                            <el-form-item class='file-list'>
                                <div v-for='(file,index) in fileList' :key='index' class='file'>
                                    <el-link :href='`/api${file}`' :underline='false' class='filename'>
                                        {{ file.slice(file.lastIndexOf('/') + 1).split('_')[0] }}
                                    </el-link>
                                    <img
                                        src='@/assets/index/del.png' alt='del' height='20' width='20'
                                        @click='removeFile(index)'>
                                </div>
                            </el-form-item>
                            <el-form-item class='btn-group'>
                                <el-button type='info' @click='closePublishWorks'>取消</el-button>
                                <el-button type='primary' @click='submit'>确定</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </div>
        </transition>
    </Teleport>
</template>
<script setup lang='ts'>
import type { Ref } from 'vue';
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue';
import { getToken } from '@/utils/auth';
import { addWorks, updateWorks } from '@/api/business/works';
import { startPageScroll } from '@/utils/sk';

const number = ref(0);
const uploadList = ref<string[]>([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + '/common/upload'); // 上传文件服务器地址
const headers = ref({ Authorization: 'Bearer ' + getToken() });
const { proxy } = getCurrentInstance();
const emits = defineEmits(['update:modelValue', 'success']);
const props = defineProps({
    modelValue: Boolean,
    competitionId: {
        type: Number,
        default: 0
    },
    initForm: {
        type: Object,
        default: null
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
        type: Array as () => Array<string>,
        default: () => ['doc', 'xls', 'ppt', 'txt', 'pdf', 'mp4']
    },
    // 大小限制(MB)
    fileSize: {
        type: Number,
        default: 5
    },
    // 数量限制
    limit: {
        type: Number,
        default: 5
    }
});
const data = reactive({
    form: {
        title: '',
        description: '',
        attachments: '',
        worksId: 0,
        competitionId: 0
    },
    rules: {
        title: [{ required: true, message: '请输入作品名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入作品介绍', trigger: 'blur' }],
        attachments: [{ required: true, message: '请上传作品附件', trigger: 'blur' }]
    }
});
const fileList: Ref<string[]> = ref([]);
const { form, rules } = toRefs(data);
const removeFile = (index: number) => {
    fileList.value.splice(index, 1);
};
const submit = () => {
    proxy.$refs['publishWorksRef'].validate((valid: boolean) => {
        if (valid) {
            form.value.attachments = fileList.value.join(',');
            form.value.competitionId = props.competitionId;
            if (!form.value?.competitionId) return proxy.$modal.msgError('比赛Id:[competitionId]不存在!');
            if (form.value?.worksId) {
                updateWorks(form.value).then(res => {
                    proxy.$modal.msgSuccess('修改成功');
                    emits('success');
                });
            } else {
                addWorks(form.value).then(res => {
                    proxy.$modal.msgSuccess('作品提交成功,请耐心等待后台管理员审核！');
                    emits('success');
                });
            }
            // console.log(form.value);
        }
    });

};
watch(() => props.modelValue, (value: boolean) => {
    if (value) {
        console.log(1);
        headers.value = { Authorization: 'Bearer ' + getToken() };
    }
}, { immediate: true });
watch(() => props.initForm, (value: any) => {
    if (value != null && JSON.stringify(value) !== '{}') {
        form.value = {
            ...value
        };
        const attachments = value?.attachments;
        if (attachments) {
            fileList.value = attachments.split(',');
        }
    }
}, { deep: true, immediate: true });
watch(() => fileList, (value) => {
    form.value.attachments = value.value.join(',');
}, { deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload(file: any) {
    // 校检文件类型
    if (props.fileType.length) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
            proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}格式文件!`);
            return false;
        }
    }
    // 校检文件大小
    if (props.fileSize) {
        const isLt = file.size / 1024 / 1024 < props.fileSize;
        if (!isLt) {
            proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
            return false;
        }
    }
    proxy.$modal.loading('正在上传文件，请稍候...');
    number.value++;
    return true;
}

// 文件个数超出
function handleExceed() {
    proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
    proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError(err: any) {
    proxy.$modal.msgError('上传文件失败');
    proxy.$modal.closeLoading();

}

// 上传成功回调
function handleUploadSuccess(res: any, file: any) {
    if (res.code === 200) {
        uploadList.value.push(res.fileName as string);
        uploadedSuccessfully();
    } else {
        number.value--;
        proxy.$modal.closeLoading();
        proxy.$modal.msgError(res.msg);
        (proxy.$refs.fileUpload as any).handleRemove(file);
        uploadedSuccessfully();
    }
}

// 上传结束处理
function uploadedSuccessfully() {
    if (number.value > 0 && uploadList.value.length === number.value) {
        fileList.value = fileList.value.filter(f => f !== '').concat(uploadList.value);
        uploadList.value = [];
        number.value = 0;
        proxy.$modal.closeLoading();
    }
}

// 重置表单
function reset() {
    form.value = {
        title: '',
        description: '',
        attachments: '',
        worksId: 0,
        competitionId: 0
    };
    number.value = 0;
    fileList.value = [];
    uploadList.value = [];
    proxy.resetForm('publishWorksRef');
}

// 关闭提交作品弹框
function closePublishWorks() {
    emits('update:modelValue', false);
    reset();
    //开启页面滚动
    startPageScroll();
}


</script>

<style scoped lang='scss'>
.publish-works-container {
    .modal {
        position: fixed;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.1);
        z-index: 1;
    }

    :deep(.el-upload-dragger) {
        padding: 20px 0;
    }

    .publish-form {
        margin-top: 20px;
        padding: 0 20px;
    }

    .file-list {
        :deep(.el-form-item__content) {
            justify-content: flex-start !important;
            flex-direction: column;
            align-items: self-start;
        }

        .file {
            height: fit-content;
            display: flex;
            align-items: center;

            .filename {
                margin-right: 10px;
            }

            img {
                cursor: pointer;
            }
        }
    }

    .btn-group {
        button {
            width: 100px;
        }

        :deep(.el-form-item__content) {
            justify-content: flex-end;
        }
    }

    .upload-area {
        width: 100%;
        border-radius: 6px;
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;

        .tips {
            font-size: 14px;
            color: #606060;
        }
    }

    :deep(.el-form-item__label) {
        font-size: 18px;
        font-weight: 400;
    }

    :deep(.el-input__wrapper) {
        box-shadow: none !important;
        background: #F2F6FC;
        height: 45px;
        font-size: 16px;
    }

    :deep(.el-textarea__inner) {
        box-shadow: none !important;
        background: #F2F6FC;
        font-size: 16px;
        min-height: 164px !important;
        resize: none;
    }

    .publish-main {
        /* 提交作品 */
        width: 855px;
        min-height: 700px;
        position: fixed;
        background: #fff;
        z-index: 2;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        border-radius: 6px;
        padding: 20px;

        .header {
            font-weight: 700;
            color: rgba(0, 0, 0, 0.8);
            display: flex;
            align-items: center;
            justify-content: space-between;

            .title {
                font-size: 22px;
            }

            .close {
                cursor: pointer;
            }
        }
    }
}
</style>
